package com.yx.filesystem.storage;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import org.json.JSONObject;

public class Transport {
	String handler;
	JSONObject jsonContent;
	boolean status=false;
	String message=null;
	
	public Transport(String handler,boolean status, String message, JSONObject jsonContent) {
		if(handler==null){
			this.handler = "";
		}else{
			this.handler = handler;
		}		
		if (jsonContent == null) {
			this.jsonContent = new JSONObject();
		} else {
			this.jsonContent = jsonContent;
		}
		this.status=status;
		this.message=message;
	}

	public Transport(BufferedInputStream socketInput) throws Exception {
		int len = readCmdLength(socketInput);
		jsonContent = readJSONObject(socketInput, len);
		this.handler=jsonContent.getString("NIO_HANDLER");
		this.status=jsonContent.getBoolean("NIO_STATUS");
		this.message=jsonContent.getString("NIO_MESSAGE");
	}

	private static final JSONObject readJSONObject(BufferedInputStream socketInput, int length)
			throws Exception {
		StringBuffer jsonStr = new StringBuffer();
		int remain = length;		
		while (remain > 0) {
			byte[] buffer= new byte[remain];
			int size = socketInput.read(buffer);
			if (size > 0) {
				jsonStr.append(byteBufferToString(buffer,size));				
				remain = remain - size;
			}
		}
		JSONObject jObj = new JSONObject(jsonStr.toString());
		return jObj;
	}

	private static final int readCmdLength(BufferedInputStream socketInput) throws Exception {
		byte[] b = new byte[6];
		int len=socketInput.read(b);
		return Integer.parseInt(byteBufferToString(b,len));		
	}

	public String getHandler() {
		return handler;
	}
	public boolean getStatus() {
		return status;
	}

	public String getMessage() {
		return message;
	}
	public JSONObject getJsonContent() {
		return this.jsonContent;
	}

	public String toSocketString()throws Exception {
		jsonContent.put("NIO_HANDLER", handler);
		jsonContent.put("NIO_STATUS", status);
		jsonContent.put("NIO_MESSAGE", message);
		String messageStr = jsonContent.toString();
		String len = "" + messageStr.getBytes().length;
		while (len.length() < 6) {
			len = "0" + len;
		}		
		return len + jsonContent.toString();
	}

	public final void write(BufferedOutputStream socketOutput) {
		try {
			byte[] buffer=toSocketString().getBytes();
			socketOutput.write(buffer);
			socketOutput.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String byteBufferToString(byte[] buffer,int len){
		return new String(buffer,0,len);		
	}
}
